package com.runvp.common.util.auth;

import com.runvp.common.model.auth.BizUserBO;
import com.runvp.common.util.ToolUtils;
import com.runvp.common.utils.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 权限获取工具类
 *
 * @author xkk update
 */
public class SecurityUtils {

    /**
     * 构建tokenKey
     *
     * @param account
     * @param type
     * @return str
     */
    public static String buildTokenKey(String account, String type) {
        return CacheConstants.LOGIN_TOKEN_KEY + CacheConstants.Separator  + type + CacheConstants.Separator + account;
    }

    /**
     * 构建token
     *
     * @param token
     * @return str
     */
    public static String buildToken(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + CacheConstants.Separator + token;
    }


    /**
     * 获取用户ID
     */
    public static long getUserId() {
        return RequestHeaderContext.userId();
    }
    /**
     * 获取用户ID
     */
    public static String getStrUserId() {
        return String.valueOf(RequestHeaderContext.userId());
    }
    /**
     * 获取用户
     */
    public static BizUserBO getUserInfo() {
        return RequestHeaderContext.getBizUserBO();
    }

    /**
     * 获取用户类型
     */
    public static String getUserType() {
        return RequestHeaderContext.getUserType();
    }

    /**
     * 获取用户来源
     */
    public static String getUserSource() {
        return RequestHeaderContext.getUserSource();
    }

    /**
     * 获取请求token
     */
    public static String getToken() {
        return getToken(ServletUtils.getRequest());
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader(CacheConstants.HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX)) {
            token = token.replace(CacheConstants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

}
